
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.FromBody;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Filter;
using CoreCms.Net.Loging;
using CoreCms.Net.IServices;
using CoreCms.Net.Utility.Helper;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using SqlSugar;
using CoreCms.Net.Services.Basic;
using CoreCms.Net.Languages;
using Microsoft.Extensions.Localization;
using System.Collections.Generic;
using CoreCms.Net.Services;

namespace CoreCms.Net.Web.Admin.Controllers
{
    /// <summary>
    /// 司机配送区域表
    ///</summary>
    [Description("司机配送区域表")]
    [Route("api/[controller]/[action]")]
    [ApiController]
    [RequiredErrorForAdmin]
    [Authorize(Permissions.Name)]

    public class corecmsdriverdeliveryareaController : ControllerBase
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly IcorecmsdriverdeliveryareaServices _corecmsdriverdeliveryareaServices;
        private readonly IcorecmsdriverServices _corecmsdriver;
        private readonly ICoreCmsAreaServices _corecmsarea;
        private readonly IStringLocalizer<LanguageResources> _stringLocalizer;


        /// <summary>
        /// 构造函数
        ///</summary>
        public corecmsdriverdeliveryareaController(IWebHostEnvironment webHostEnvironment
            , IcorecmsdriverdeliveryareaServices corecmsdriverdeliveryareaServices
            , IcorecmsdriverServices corecmsdriver
            , ICoreCmsAreaServices corecmsarea
            , IStringLocalizer<LanguageResources> stringLocalizer
            )
        {
            _webHostEnvironment = webHostEnvironment;
            _corecmsdriverdeliveryareaServices = corecmsdriverdeliveryareaServices;
            _corecmsdriver = corecmsdriver;
            _corecmsarea = corecmsarea;
            _stringLocalizer = stringLocalizer;
            _stringLocalizer.SetStringLocalizer();
        }

        #region 获取列表============================================================
        // POST: Api/corecmsdriverdeliveryarea/GetPageList
         /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("获取列表")]
        public async Task<AdminUiCallBack> GetPageList()
        {
            var jm = new AdminUiCallBack();
            var pageCurrent = Request.Form["page"].FirstOrDefault().ObjectToInt(1);
            var pageSize = Request.Form["limit"].FirstOrDefault().ObjectToInt(30);
            var where = PredicateBuilder.True<corecmsdriverdeliveryarea>();
            //获取排序字段
            var orderField = Request.Form["orderField"].FirstOrDefault();

            Expression<Func<corecmsdriverdeliveryarea, object>> orderEx = orderField switch
            {
                "id" => p => p.id,"driverId" => p => p.driverId,"areaId" => p => p.areaId,"createTime" => p => p.createTime,
                _ => p => p.id
            };

            //设置排序方式
            var orderDirection = Request.Form["orderDirection"].FirstOrDefault();
            var orderBy = orderDirection switch
            {
                "asc" => OrderByType.Asc,
                "desc" => OrderByType.Desc,
                _ => OrderByType.Desc
            };
            //查询筛选
			
			// int
			var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
			//司机 int
			var driverId = Request.Form["driverId"].FirstOrDefault().ObjectToInt(0);
            if (driverId > 0)
            {
                where = where.And(p => p.driverId == driverId);
            }
			//地区id int
			var areaId = Request.Form["areaId"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(areaId))
            {
                where = where.And(p => p.areaId == areaId);
            }
			//创建时间 datetime
			var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                if (createTime.Contains("到"))
                {
                    var dts = createTime.Split("到");
                    var dtStart = dts[0].Trim().ObjectToDate();
                    where = where.And(p => p.createTime > dtStart);
                    var dtEnd = dts[1].Trim().ObjectToDate();
                    where = where.And(p => p.createTime < dtEnd);
                }
                else
                {
                    var dt = createTime.ObjectToDate();
                    where = where.And(p => p.createTime > dt);
                }
            }
            //获取数据
            var list = await _corecmsdriverdeliveryareaServices.QueryPageAsync(where, orderEx, orderBy, pageCurrent, pageSize, true);
            // 地区表 街道信息
            var areas = await _corecmsarea.QueryListByClauseAsync(p => p.depth == 2, p => p.postalCode, OrderByType.Asc);

            foreach (var item in list)
            {
                //item.areaId = CommonHelper.GetCaptureInterceptedText(item.areaId, ",");
                string[] areaArr = item.areaId.Split(",");

                IEnumerable<string> names = areaArr
                   .Select(id => areas.FirstOrDefault(area => area.id == int.Parse(id)))
                   .Where(area => area != null)
                   .Select(area => area.name);
                item.areaName = string.Join(", ", names);
            }

            //返回数据
            jm.data = list;
            jm.code = 0;
            jm.count = list.TotalCount;
            jm.msg = "数据调用成功!".t();
            return jm;
        }
        #endregion

        #region 首页数据============================================================
        // POST: Api/corecmsdriverdeliveryarea/GetIndex
        /// <summary>
        /// 首页数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("首页数据")]
        public AdminUiCallBack GetIndex()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };

            /*//司机列表
            var drivers = await _corecmsdriver.QueryListByClauseAsync(p => p.active == true, p => p.createTime, OrderByType.Desc);
            // 地区表 街道信息
            var areas = await _corecmsarea.QueryListByClauseAsync(p => p.depth == 2, p => p.id, OrderByType.Desc);

            jm.data = new
            {
                areas,
                drivers
            };*/
            return jm;
        }
        #endregion

        #region 创建数据============================================================
        // POST: Api/corecmsdriverdeliveryarea/GetCreate
        /// <summary>
        /// 创建数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("创建数据")]
        public async Task<AdminUiCallBack> GetCreateAsync()
        {
            //返回数据
            var jm = new AdminUiCallBack { code = 0 };
            //司机列表
            var drivers = await _corecmsdriver.QueryListByClauseAsync(p => p.active == true, p => p.createTime, OrderByType.Desc);
            // 地区表 街道信息
            var areas = await _corecmsarea.QueryListByClauseAsync(p => p.depth == 2, p => p.postalCode, OrderByType.Asc);

            //过滤已经选择的区域
            var driverdeliveryareas = await _corecmsdriverdeliveryareaServices.QueryAsync();
            if (driverdeliveryareas.Count > 0)
            {
                //driverdeliveryareas.ForEach(f => f.areaId = CommonHelper.GetCaptureInterceptedText(f.areaId, ","));
                var nuArea = string.Join(",", driverdeliveryareas.Select(s => s.areaId).ToList());
                // 过滤已经选择的数据
                areas = areas.Where(w => !nuArea.Contains(w.id.ToString())).ToList();
                /*areas.ForEach(f => f.name += $"({f.postalCode})");*/
            }

            jm.data = new
            {
                areas,
                drivers
            };
            return jm;
        }
        #endregion

        #region 创建提交============================================================
        // POST: Api/corecmsdriverdeliveryarea/DoCreate
        /// <summary>
        /// 创建提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("创建提交")]
        public async Task<AdminUiCallBack> DoCreate([FromBody] corecmsdriverdeliveryarea entity)
        {
            var jm = new AdminUiCallBack();
            if (entity.driverId == null || entity.driverId <= 0)
            {
                jm.msg = "请选择司机";
                return jm;
            }
            var model = await _corecmsdriverdeliveryareaServices.QueryByClauseAsync(p => p.driverId == entity.driverId);
            if(model != null)
            {
                jm.msg = "司机数据已存在,请进行编辑";
                return jm;
            }

            entity.areaId = entity.areaId.Replace("，", ",");
            List<string> temp = entity.areaId.Split(",").ToList();
            bool result = temp.All(s => s.Length == 3);
            if (!result) {
                jm.msg = "输入的长度不对";
                return jm;
            }

            //entity.areaId = "," + entity.areaId + ",";
            jm = await _corecmsdriverdeliveryareaServices.InsertAsync(entity);
            return jm;
        }
        #endregion

        #region 编辑数据============================================================
        // POST: Api/corecmsdriverdeliveryarea/GetEdit
        /// <summary>
        /// 编辑数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑数据")]
        public async Task<AdminUiCallBack> GetEdit([FromBody]FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _corecmsdriverdeliveryareaServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            //model.areaId = CommonHelper.GetCaptureInterceptedText(model.areaId, ",");
            //司机列表
            var drivers = await _corecmsdriver.QueryListByClauseAsync(p => p.active == true, p => p.createTime, OrderByType.Desc);
            // 地区表 街道信息
            var areas = await _corecmsarea.QueryListByClauseAsync(p => p.depth == 2, p => p.postalCode, OrderByType.Asc);


            //过滤已经选择的区域 过滤掉除了司机已选的区域
            var driverdeliveryareas = await _corecmsdriverdeliveryareaServices.QueryListByClauseAsync(w=>w.driverId != model.driverId);
            if (driverdeliveryareas.Count > 0)
            {
                //driverdeliveryareas.ForEach(f => f.areaId = CommonHelper.GetCaptureInterceptedText(f.areaId, ","));
                var nuArea = string.Join(",", driverdeliveryareas.Select(s => s.areaId).ToList());
                // 过滤已经选择的数据
                areas = areas.Where(w => !nuArea.Contains(w.id.ToString())).ToList();
                /*areas.ForEach(f => f.name += $"({f.postalCode})");*/
            }

            jm.data = new
            {
                model,
                areas,
                drivers
            };           
            jm.code = 0;
            return jm;
        }
        #endregion

        #region 编辑提交============================================================
        // POST: Api/corecmsdriverdeliveryarea/Edit
        /// <summary>
        /// 编辑提交
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("编辑提交")]
        public async Task<AdminUiCallBack> DoEdit([FromBody] corecmsdriverdeliveryarea entity)
        {
            var jm = new AdminUiCallBack();
            if (entity.driverId == null || entity.driverId <= 0)
            {
                jm.msg = "请选择司机";
                return jm;
            }
            var model = await _corecmsdriverdeliveryareaServices.QueryByClauseAsync(p => p.id == entity.id);
            if (model == null)
            {
                jm.msg = "数据不存在".t();
                return jm;
            }

            entity.areaId = entity.areaId.Replace("，", ",");
            List<string> temp = entity.areaId.Split(",").ToList();
            bool result = temp.All(s => s.Length == 3);
            if (!result)
            {
                jm.msg = "输入的长度不对";
                return jm;
            }

            var allAreas = await _corecmsdriverdeliveryareaServices.QueryListByClauseAsync(p=>p.id != entity.id);
            var allAreaIds = allAreas.Select(s => s.areaId).ToList();

            var lstStr = temp.Where(t => allAreaIds.Any(a => a.Contains(t))).ToList();
            if (lstStr.Count > 0)
            {
                jm.msg = "邮编重复:" + string.Join(",", lstStr);
                return jm;
            }

            entity.updateTime = DateTime.Now;
            //entity.areaId = "," + entity.areaId + ",";
            jm = await _corecmsdriverdeliveryareaServices.UpdateAsync(entity);
            return jm;
        }
        #endregion

        #region 删除数据============================================================
        // POST: Api/corecmsdriverdeliveryarea/DoDelete/10
        /// <summary>
        /// 单选删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("单选删除")]
        public async Task<AdminUiCallBack> DoDelete([FromBody]FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _corecmsdriverdeliveryareaServices.ExistsAsync(p => p.id == entity.id, true);
            if (!model)
            {
                jm.msg = GlobalConstVars.DataisNo;
				return jm;
            }
            jm = await _corecmsdriverdeliveryareaServices.DeleteByIdAsync(entity.id);

            return jm;
        }
        #endregion

        #region 批量删除============================================================
        // POST: Api/corecmsdriverdeliveryarea/DoBatchDelete/10,11,20
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("批量删除")]
        public async Task<AdminUiCallBack> DoBatchDelete([FromBody]FMArrayIntIds entity)
        {
            var jm = await _corecmsdriverdeliveryareaServices.DeleteByIdsAsync(entity.id);
            return jm;
        }

        #endregion

        #region 预览数据============================================================
        // POST: Api/corecmsdriverdeliveryarea/GetDetails/10
        /// <summary>
        /// 预览数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("预览数据")]
        public async Task<AdminUiCallBack> GetDetails([FromBody]FMIntId entity)
        {
            var jm = new AdminUiCallBack();

            var model = await _corecmsdriverdeliveryareaServices.QueryByIdAsync(entity.id, false);
            if (model == null)
            {
                jm.msg = "不存在此信息";
                return jm;
            }
            jm.code = 0;
            jm.data = model;

            return jm;
        }
        #endregion

        #region 选择导出============================================================
        // POST: Api/corecmsdriverdeliveryarea/SelectExportExcel/10
        /// <summary>
        /// 选择导出
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Description("选择导出")]
        public async Task<AdminUiCallBack> SelectExportExcel([FromBody]FMArrayIntIds entity)
        {
            var jm = new AdminUiCallBack();

            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var mySheet = book.CreateSheet("Sheet1");
            //获取list数据
            var listModel = await _corecmsdriverdeliveryareaServices.QueryListByClauseAsync(p => entity.id.Contains(p.id), p => p.id, OrderByType.Asc, true);
            //给sheet1添加第一行的头部标题
            var headerRow = mySheet.CreateRow(0);
            var headerStyle = ExcelHelper.GetHeaderStyle(book);

            var cell0 = headerRow.CreateCell(0);
            cell0.SetCellValue("");
            cell0.CellStyle = headerStyle;
            mySheet.SetColumnWidth(0, 10 * 256);

            var cell1 = headerRow.CreateCell(1);
            cell1.SetCellValue("司机");
            cell1.CellStyle = headerStyle;
            mySheet.SetColumnWidth(1, 10 * 256);

            var cell2 = headerRow.CreateCell(2);
            cell2.SetCellValue("地区id");
            cell2.CellStyle = headerStyle;
            mySheet.SetColumnWidth(2, 10 * 256);

            var cell3 = headerRow.CreateCell(3);
            cell3.SetCellValue("创建时间");
            cell3.CellStyle = headerStyle;
            mySheet.SetColumnWidth(3, 10 * 256);

            headerRow.Height = 30 * 20;
            var commonCellStyle = ExcelHelper.GetCommonStyle(book);

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listModel.Count; i++)
            {
                var rowTemp = mySheet.CreateRow(i + 1);

                    var rowTemp0 = rowTemp.CreateCell(0);
                        rowTemp0.SetCellValue(listModel[i].id.ToString());
                        rowTemp0.CellStyle = commonCellStyle;

                    var rowTemp1 = rowTemp.CreateCell(1);
                        rowTemp1.SetCellValue(listModel[i].driverId.ToString());
                        rowTemp1.CellStyle = commonCellStyle;

                    var rowTemp2 = rowTemp.CreateCell(2);
                        rowTemp2.SetCellValue(listModel[i].areaId.ToString());
                        rowTemp2.CellStyle = commonCellStyle;

                    var rowTemp3 = rowTemp.CreateCell(3);
                        rowTemp3.SetCellValue(listModel[i].createTime.ToString());
                        rowTemp3.CellStyle = commonCellStyle;

            }
            // 导出excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-corecmsdriverdeliveryarea导出(选择结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        #region 查询导出============================================================
        // POST: Api/corecmsdriverdeliveryarea/QueryExportExcel/10
        /// <summary>
        /// 查询导出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Description("查询导出")]
        public async Task<AdminUiCallBack> QueryExportExcel()
        {
            var jm = new AdminUiCallBack();

            var where = PredicateBuilder.True<corecmsdriverdeliveryarea>();
                //查询筛选
			
			// int
			var id = Request.Form["id"].FirstOrDefault().ObjectToInt(0);
            if (id > 0)
            {
                where = where.And(p => p.id == id);
            }
			//司机 int
			var driverId = Request.Form["driverId"].FirstOrDefault().ObjectToInt(0);
            if (driverId > 0)
            {
                where = where.And(p => p.driverId == driverId);
            }
			//地区id int
			var areaId = Request.Form["areaId"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(areaId))
            {
                where = where.And(p => p.areaId == areaId);
            }
			//创建时间 datetime
			var createTime = Request.Form["createTime"].FirstOrDefault();
            if (!string.IsNullOrEmpty(createTime))
            {
                var dt = createTime.ObjectToDate();
                where = where.And(p => p.createTime > dt);
            }
            //获取数据
            //创建Excel文件的对象
            var book = new HSSFWorkbook();
            //添加一个sheet
            var mySheet = book.CreateSheet("Sheet1");
            //获取list数据
            var listModel = await _corecmsdriverdeliveryareaServices.QueryListByClauseAsync(where, p => p.id, OrderByType.Asc, true);
            //给sheet1添加第一行的头部标题
                var headerRow = mySheet.CreateRow(0);
            var headerStyle = ExcelHelper.GetHeaderStyle(book);
            
            var cell0 = headerRow.CreateCell(0);
            cell0.SetCellValue("");
            cell0.CellStyle = headerStyle;
            mySheet.SetColumnWidth(0, 10 * 256);
			
            var cell1 = headerRow.CreateCell(1);
            cell1.SetCellValue("司机");
            cell1.CellStyle = headerStyle;
            mySheet.SetColumnWidth(1, 10 * 256);
			
            var cell2 = headerRow.CreateCell(2);
            cell2.SetCellValue("地区id");
            cell2.CellStyle = headerStyle;
            mySheet.SetColumnWidth(2, 10 * 256);
			
            var cell3 = headerRow.CreateCell(3);
            cell3.SetCellValue("创建时间");
            cell3.CellStyle = headerStyle;
            mySheet.SetColumnWidth(3, 10 * 256);
			

            headerRow.Height = 30 * 20;
            var commonCellStyle = ExcelHelper.GetCommonStyle(book);

            //将数据逐步写入sheet1各个行
            for (var i = 0; i < listModel.Count; i++)
            {
                var rowTemp = mySheet.CreateRow(i + 1);


            var rowTemp0 = rowTemp.CreateCell(0);
            rowTemp0.SetCellValue(listModel[i].id.ToString());
            rowTemp0.CellStyle = commonCellStyle;



            var rowTemp1 = rowTemp.CreateCell(1);
            rowTemp1.SetCellValue(listModel[i].driverId.ToString());
            rowTemp1.CellStyle = commonCellStyle;



            var rowTemp2 = rowTemp.CreateCell(2);
            rowTemp2.SetCellValue(listModel[i].areaId.ToString());
            rowTemp2.CellStyle = commonCellStyle;



            var rowTemp3 = rowTemp.CreateCell(3);
            rowTemp3.SetCellValue(listModel[i].createTime.ToString());
            rowTemp3.CellStyle = commonCellStyle;


            }
            // 写入到excel
            string webRootPath = _webHostEnvironment.WebRootPath;
            string tpath = "/files/" + DateTime.Now.ToString("yyyy-MM-dd") + "/";
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-corecmsdriverdeliveryarea导出(查询结果).xls";
            string filePath = webRootPath + tpath;
            DirectoryInfo di = new DirectoryInfo(filePath);
            if (!di.Exists)
            {
                di.Create();
            }
            FileStream fileHssf = new FileStream(filePath + fileName, FileMode.Create);
            book.Write(fileHssf);
            fileHssf.Close();

            jm.code = 0;
            jm.msg = GlobalConstVars.ExcelExportSuccess;
            jm.data = tpath + fileName;

            return jm;
        }
        #endregion

        

    }
}
